<template>
  <el-dialog v-model="visible" :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" draggable>
    <el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="120px">
      <el-form-item prop="title" label="标题">
        <el-input v-model="dataForm.title" placeholder="标题"></el-input>
      </el-form-item>
      <el-form-item prop="orgId" label="所属机构">
        <el-tree-select
            v-model="dataForm.orgId"
            :data="orgList"
            value-key="id"
            @change="orgHandle($event)"
            check-strictly
            :render-after-expand="false"
            :props="{ label: 'name', children: 'children' }"
            style="width: 100%"
            clearable
        />
      </el-form-item>
      <el-form-item prop="communityId" label="所属社区">
        <el-tree-select
            v-model="dataForm.communityId"
            :data="communityList"
            value-key="id"
            check-strictly
            :render-after-expand="false"
            :props="{ label: 'communityName', children: 'children' }"
            style="width: 100%"
            clearable
        />
      </el-form-item>
      <el-form-item prop="content" label="内容">
        <el-input v-model="dataForm.content" type="textarea" placeholder="内容"></el-input>
      </el-form-item>

      <el-form-item label="图片" prop="image" >
        <el-upload
            v-model:file-list="fileList"
            class="upload-demo"
            action=""
            multiple
            :on-change="handleelchange"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :limit="1"
            :auto-upload="false"
        >
          <el-button type="primary">上传图片</el-button>
          <template #tip>
            <div class="el-upload__tip">
              jpg/png 不能超过 500KB.
            </div>
          </template>
        </el-upload>
      </el-form-item>

    </el-form>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="submitHandle()">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import {ElMessage,ElMessageBox, UploadProps,UploadUserFile} from 'element-plus/es'
import { invitationApi, invitationSubmitApi } from '@/api/new/invitation'
import {useOrgListApi} from "@/api/sys/orgs";
import { importUpload } from '@/api/upload/exportUpload'
import {orgCommunityListApi} from "@/api/new/community";



const emit = defineEmits(['refreshDataList'])

const visible = ref(false)
const menuListTree = ref()
const dataFormRef = ref()
const orgList = ref([])
const communityList = ref([])

const dataForm = reactive({
  id: '',
  title: '',
  merchantCode: '',
  url: '',
  communityId: '',
  orgId: undefined,
  content: ''
})

const fileList = ref<UploadUserFile[]>([

])

const init = async (id?: number) => {
  visible.value = true
  dataForm.id = ''

  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields()
    fileList.value = []
  }
  if (menuListTree.value) {
    menuListTree.value.setCheckedKeys([])
  }

  console.log(id)

  getOrgList()

  // id 存在则为修改
  if (id) {
    getInvitation(id)
  }
}



// 获取信息
const getInvitation = (id: number) => {
  invitationApi(id).then(res => {
    Object.assign(dataForm, res.data)
    fileList.value = res.data.images
  })
}

// 获取机构列表
const getOrgList = () => {
  return useOrgListApi().then(res => {
    orgList.value = res.data
  })
}

const orgHandle = (val: any) => {
  getOrgCommunityList(val)
}

const getOrgCommunityList = (orgId: any) => {
  const data = {
    orgId : orgId
  }
  orgCommunityListApi(data).then(res => {
    communityList.value = res.data
  })
}

const handleelchange:UploadProps['onChange'] =(file:any) => {

  let formdata = new FormData()

  formdata.append("file", file.raw)  //将文件加进formdata



  importUpload("/sys/file/upload",formdata).then(res=>{
    if(res){

      dataForm.url = res.data.url

      ElMessage.success({
        message: '上传成功',
        duration: 500,
      })
    }
  })

}


const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
  console.log(file, uploadFiles)
}

const handlePreview: UploadProps['onPreview'] = (uploadFile) => {
  console.log(uploadFile)
}


const beforeRemove: UploadProps['beforeRemove'] = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
      `Cancel the transfer of ${uploadFile.name} ?`
  ).then(
      () => true,
      () => false
  )
}

const dataRules = ref({
  content: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
})



// 表单提交
const submitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false
    }
    // dataForm.menuIdList = [...menuListTree.value.getHalfCheckedKeys(), ...menuListTree.value.getCheckedKeys()]

    invitationSubmitApi(dataForm).then(() => {
      ElMessage.success({
        message: '操作成功',
        duration: 500,
        onClose: () => {
          visible.value = false
          emit('refreshDataList')
        }
      })
    })
  })
}

defineExpose({
  init
})

</script>
